<template>
  <div class="setting-page">
    <div class="page-content">
      <el-card class="settings-card">
        <!-- 选项卡导航 -->
        <el-tabs v-model="activeName" type="card" class="settings-tabs">
          <!-- 基本信息设置 -->
          <el-tab-pane label="基本信息设置" name="part1">
            <div class="tab-content">
              <el-form ref="formRef" :model="form" label-width="140px" class="settings-form">
                <!-- 公司名称 -->
                <el-form-item label="公司名称" prop="company_name" class="form-item">
                  <el-input v-model.trim="form.company_name" placeholder="请输入公司名称" />
                </el-form-item>

                <!-- 备案号 -->
                <el-form-item label="备案号" prop="company_icp" class="form-item">
                  <el-input v-model.trim="form.company_icp" placeholder="请输入备案号" />
                </el-form-item>

                <!-- 单元ID -->
                <el-form-item label="单元ID" prop="company_id" class="form-item">
                  <el-input v-model.trim="form.company_id" placeholder="请输入单元ID" />
                </el-form-item>

                <!-- 推广城市 -->
                <el-form-item label="推广城市" prop="promotion_city" class="form-item">
                  <el-input v-model.trim="form.promotion_city" placeholder="请输入推广城市" />
                </el-form-item>

                <!-- 时间节点 -->
                <el-form-item label="时间节点" class="form-item">
                  <el-input v-model.trim="form.time_node" placeholder="请输入时间节点" />
                </el-form-item>

                <!-- IP白名单 -->
                <el-form-item label="IP白名单" prop="secured_ip" class="form-item">
                  <div class="textarea-with-tooltip">
                    <el-input v-model.trim="form.secured_ip" type="textarea" :rows="5" placeholder="请输入IP白名单，一行一个"
                      class="ip-textarea" />
                    <el-tooltip placement="right" effect="dark">
                      <template #content>
                        <div class="tooltip-content">
                          <p>一行一个IP地址</p>
                        </div>
                      </template>
                      <el-icon class="tooltip-icon">
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </div>
                </el-form-item>

                <!-- 底部信息 -->
                <el-form-item label="底部信息" prop="company_copyright" class="form-item">
                  <el-input v-model.trim="form.company_copyright" type="textarea" :rows="5" placeholder="请输入底部版权信息" />
                </el-form-item>

                <!-- 滚动文字 -->
                <el-form-item label="滚动文字" prop="scrollbar" class="form-item">
                  <el-input v-model.trim="form.scrollbar" type="textarea" :rows="5" placeholder="请输入滚动文字内容" />
                </el-form-item>

                <el-form-item label="公司logo" prop="logo">
                  <el-upload :action="uploadAction" :headers="uploadHeaders" :on-success="handleAvatarUploadSuccess"
                    :on-error="handleUploadError" :before-upload="beforeAvatarUpload" :on-remove="handleAvatarRemove"
                    :on-preview="handleAvatarPreview" :file-list="avatarFileList" list-type="picture-card" :limit="1"
                    :on-exceed="handleAvatarExceed" class="logo-upload">
                    <el-icon class="upload-icon">
                      <Plus />
                    </el-icon>
                    <template #tip>
                      <div class="el-upload__tip">
                        支持jpg/png格式，只能上传1张，不超过2MB
                      </div>
                    </template>
                  </el-upload>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 上传设置 -->
          <el-tab-pane label="上传设置" name="part3">
            <div class="tab-content">
              <el-form ref="formRef" :model="form" label-width="140px" class="settings-form">
                <!-- 上传类型 -->
                <el-form-item label="上传类型" prop="upload_type" class="form-item">
                  <el-radio-group v-model="form.upload_type">
                    <el-radio label="1">本地存储</el-radio>
                    <el-radio label="2">阿里云OSS</el-radio>
                  </el-radio-group>
                </el-form-item>

                <template v-if="form.upload_type === '2'">
                  <!-- bucket -->
                  <el-form-item label="Bucket" prop="bucket" class="form-item">
                    <el-input v-model.trim="form.bucket" placeholder="请输入Bucket名称" />
                  </el-form-item>

                  <!-- accesskeyid -->
                  <el-form-item label="AccessKeyId" prop="accesskeyid" class="form-item">
                    <el-input v-model.trim="form.accesskeyid" placeholder="请输入AccessKeyId" />
                  </el-form-item>

                  <!-- accesskeysecret -->
                  <el-form-item label="AccessKeySecret" prop="accesskeysecret" class="form-item">
                    <el-input v-model.trim="form.accesskeysecret" placeholder="请输入AccessKeySecret" type="password" />
                  </el-form-item>

                  <!-- endpoint -->
                  <el-form-item label="Endpoint" prop="endpoint" class="form-item">
                    <el-input v-model.trim="form.endpoint" placeholder="请输入Endpoint" />
                  </el-form-item>

                  <!-- oss_domain -->
                  <el-form-item label="OSS域名" prop="oss_domain" class="form-item">
                    <el-input v-model.trim="form.oss_domain" placeholder="请输入OSS域名" />
                  </el-form-item>
                </template>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 短信设置 -->
          <el-tab-pane label="短信设置" name="part4">
            <div class="tab-content">
              <el-form ref="formRef" :model="form" label-width="140px" class="settings-form">
                <!-- 短信签名 -->
                <el-form-item label="短信签名" prop="sms_signname" class="form-item">
                  <el-input v-model="form.sms_signname" placeholder="请输入短信签名" />
                </el-form-item>

                <!-- 短信通道 -->
                <el-form-item label="短信通道" prop="sms_channel" class="form-item">
                  <el-radio-group v-model="form.sms_channel" @change="handleSmsChannelChange">
                    <el-radio v-for="item in sms" :key="item.id" :label="item.id">
                      {{ item.sms_name }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>

                <!-- 平台账号 -->
                <el-form-item label="平台账号" class="form-item">
                  <el-input v-model.trim="form.account" placeholder="请输入平台账号" />
                </el-form-item>

                <!-- 平台密码 -->
                <el-form-item label="平台密码" class="form-item">
                  <el-input v-model.trim="form.password" type="password" placeholder="请输入平台密码" />
                </el-form-item>

                <!-- 接口秘钥 -->
                <el-form-item label="接口秘钥" class="form-item">
                  <el-input v-model.trim="form.apikey" placeholder="请输入接口秘钥" />
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- 保存按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="onSubmit" :loading="loading" class="save-button">
            保存设置
          </el-button>
          <el-button @click="resetForm" class="reset-button">
            重置
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewDialogVisible" title="图片预览" width="500px" append-to-body>
      <div style="text-align: center;background-color: #f2f2f2;">
        <img :src="previewImageUrl" style="max-width: 100%; max-height: 400px;" alt="预览图片" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, QuestionFilled } from '@element-plus/icons-vue'
import { getSetting, editSetting, } from '@/api/setting'
// 响应式数据
const activeName = ref('part1')
const formRef = ref()
const loading = ref(false)

// 表单数据
const form = reactive({
  company_name: '',
  company_copyright: '',
  company_id: '',
  promotion_city: '',
  secured_ip: '',
  company_icp: '',
  scrollbar: '',
  upload_type: '1',
  bucket: '',
  accesskeyid: '',
  accesskeysecret: '',
  endpoint: '',
  oss_domain: '',
  sms_channel: 1,
  sms_signname: '',
  logo: '',
  time_node: '',
  account: '',
  password: '',
  apikey: ''
})

// 短信通道列表
const sms = ref([])
const sms_channel = ref(1)

// 上传相关数据
const uploadAction = ref(process.env.NODE_ENV === 'development' ? '/api/api/common/upload' : '/api/common/upload')
const uploadHeaders = ref({})
const avatarFileList = ref([])

// 图片预览相关数据
const previewDialogVisible = ref(false)
const previewImageUrl = ref('')

// 初始化数据
onMounted(() => {
  loadSettings()
})



// 加载设置数据
const loadSettings = async () => {
  try {
    const response = await getSetting()

    if (response && response.data && response.data.config) {
      const config = response.data.config
      form.company_name = config.company_name || ''
      form.company_copyright = config.company_copyright || ''
      form.company_id = config.company_id || ''
      form.promotion_city = config.promotion_city || ''
      form.secured_ip = config.secured_ip || ''
      form.company_icp = config.company_icp || ''
      form.scrollbar = config.scrollbar || ''
      form.upload_type = config.upload_type || '1'
      form.bucket = config.bucket || ''
      form.accesskeyid = config.accesskeyid || ''
      form.accesskeysecret = config.accesskeysecret || ''
      form.endpoint = config.endpoint || ''
      form.oss_domain = config.oss_domain || ''
      form.sms_channel = config.sms_channel || 1
      form.sms_signname = config.sms_signname || ''
      form.logo = config.logo || ''
      form.time_node = config.time_node || ''

      // 处理短信通道数据
      if (response.data.sms && response.data.sms.length > 0) {
        sms.value = response.data.sms
        const currentSms = response.data.sms[Number(config.sms_channel) - 1]
        if (currentSms) {
          form.account = currentSms.account || ''
          form.password = currentSms.password || ''
          form.apikey = currentSms.apikey || ''
        }
        sms_channel.value = Number(config.sms_channel) - 1
      }

      // 处理logo文件列表
      if (config.logo) {
        avatarFileList.value = [{
          name: config.logo,
          url: config.logo,
          uid: Date.now()
        }]
      } else {
        avatarFileList.value = []
      }
    }
  } catch (error) {
    console.error('加载设置失败:', error)
    ElMessage.error('加载设置失败')
  }
}

// 短信通道变更处理
const handleSmsChannelChange = (val) => {
  sms_channel.value = Number(val) - 1
  const currentSms = sms.value[Number(val) - 1]
  if (currentSms) {
    form.account = currentSms.account || ''
    form.password = currentSms.password || ''
    form.apikey = currentSms.apikey || ''
  }
}

// 提交设置
const onSubmit = async () => {
  try {
    loading.value = true

    await editSetting(form)

    ElMessage.success('设置保存成功')
    // 重新获取设置
    await loadSettings()
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  loadSettings()
}

// ==================== Logo上传相关方法 ====================

// Logo上传前检查
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('Logo只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('Logo大小不能超过 2MB!')
    return false
  }
  return true
}

// Logo上传成功
const handleAvatarUploadSuccess = (response, file) => {


  if (response.status) {
    ElMessage.success('Logo上传成功')
    form.logo = response.name

    // 更新文件对象的URL
    file.url = response.name
    file.response = response
  } else {
    ElMessage.error(response.msg || 'Logo上传失败')
  }
}

// Logo上传失败
const handleUploadError = (error, file) => {
  console.error('Logo上传失败:', error)
  ElMessage.error('Logo上传失败，请重试')
}

// Logo移除
const handleAvatarRemove = (file) => {
  form.logo = ''
  ElMessage.success('Logo已移除')
}

// Logo预览
const handleAvatarPreview = (file) => {
  previewImageUrl.value = file.url || file.response?.name || ''
  previewDialogVisible.value = true
}

// Logo超出数量限制
const handleAvatarExceed = (files, fileList) => {
  ElMessage.warning('只能上传1张Logo图片')
}

</script>

<style scoped>
.setting-page {
  background-color: var(--theme-bg-tertiary);
}

.page-content {
  height: 100%;
}

.settings-card {
  height: 100%;
  border-radius: 8px;
  box-shadow: var(--theme-shadow-base);
  border: 1px solid var(--theme-border-light);
  background: var(--theme-bg-primary);
}

.settings-card :deep(.el-card__body) {
  padding: 0;
  height: 100%;
  overflow: hidden;
}

/* 选项卡样式 */
.settings-tabs {
  height: 100%;
}

.settings-tabs :deep(.el-tabs__header) {
  margin: 0;
  padding: 0 20px;
  background: var(--theme-bg-primary);
  border-bottom: 1px solid var(--theme-border-light);
}

.settings-tabs :deep(.el-tabs__nav-wrap) {
  padding: 0;
}

.settings-tabs :deep(.el-tabs__nav-wrap::after) {
  background-color: var(--theme-border-light);
}

.settings-tabs :deep(.el-tabs__item) {
  padding: 0 20px;
  font-size: 14px;
  color: var(--theme-text-regular);
}

.settings-tabs :deep(.el-tabs__item.is-active) {
  color: var(--theme-primary);
  font-weight: 500;
}

.settings-tabs :deep(.el-tabs__active-bar) {
  background-color: var(--theme-primary);
}

.settings-tabs :deep(.el-tabs__content) {
  height: calc(100% - 51px);
  overflow-y: auto;
}

.settings-tabs :deep(.el-tab-pane) {
  height: 100%;
}

/* 标签页内容 */
.tab-content {
  padding: 30px;
  height: 100%;
  overflow-y: auto;
}

/* 表单样式 */
.settings-form {
  max-width: 800px;
}

.form-item {
  margin-bottom: 24px;
}

.form-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--theme-text-regular);
  font-size: 14px;
}

.form-item :deep(.el-input__wrapper) {
  border-radius: 6px;
  border-color: var(--theme-border-base);
}

.form-item :deep(.el-input__wrapper:hover) {
  border-color: var(--theme-border-dark);
}

.form-item :deep(.el-input__wrapper.is-focus) {
  border-color: var(--theme-primary);
  box-shadow: 0 0 0 1px var(--theme-primary) inset;
}

.form-item :deep(.el-input__inner) {
  color: var(--theme-text-regular);
}

.form-item :deep(.el-input__inner::placeholder) {
  color: var(--theme-text-placeholder);
}

.form-item :deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

.form-item :deep(.el-radio) {
  margin-right: 0;
}

.form-item :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: var(--theme-primary);
  border-color: var(--theme-primary);
}

.form-item :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: var(--theme-primary);
}

/* 工具提示样式 */
.textarea-with-tooltip {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.ip-textarea {
  flex: 1;
}

.tooltip-icon {
  color: var(--theme-text-secondary);
  cursor: help;
  font-size: 16px;
  margin-top: 8px;
  transition: color 0.3s ease;
}

.tooltip-icon:hover {
  color: var(--theme-primary);
}

.tooltip-content {
  font-size: 13px;
  line-height: 1.4;
}

.tooltip-content p {
  margin: 0;
}

/* 按钮样式 */
.form-actions {
  margin-top: 40px;
  padding: 20px 30px;
  border-top: 1px solid var(--theme-border-light);
  background: var(--theme-bg-primary);
  display: flex;
  justify-content: center;
  gap: 16px;
}

.save-button {
  width: 120px;
  height: 40px;
  font-size: 14px;
  font-weight: 500;
  background: var(--theme-primary);
  border-color: var(--theme-primary);
}

.save-button:hover {
  background: var(--theme-primary-light);
  border-color: var(--theme-primary-light);
}

.reset-button {
  width: 100px;
  height: 40px;
  font-size: 14px;
  font-weight: 500;
  background: var(--theme-bg-primary);
  border-color: var(--theme-border-base);
  color: var(--theme-text-regular);
}

.reset-button:hover {
  background: var(--theme-bg-secondary);
  border-color: var(--theme-border-dark);
  color: var(--theme-primary);
}

/* LOGO上传样式 */
.logo-upload {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.logo-upload :deep(.el-upload-list--picture-card) {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.logo-upload :deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  border: 1px dashed var(--theme-border-base);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f2f2f2;
}

.logo-upload :deep(.el-upload--picture-card:hover) {
  border-color: var(--theme-primary);
}

.logo-upload :deep(.el-upload-list__item) {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;

  background: #f2f2f2;
}

.logo-upload :deep(.el-upload-list__item-thumbnail) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-icon {
  font-size: 28px;
  color: var(--theme-text-secondary);
}

.upload-tip {
  font-size: 12px;
  color: var(--theme-text-secondary);
  line-height: 1.4;
  margin-top: 8px;
}

.upload-tip p {
  margin: 0;
}
</style>
